package com.buobao.bmall.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Arrays;


/**
 * 拦截打印web请求日志
 */
@Aspect
@Component
public class WebLogFilter {

    private final Logger log = LoggerFactory.getLogger(WebLogFilter.class);

    @Pointcut("execution(public * com.buobao.bmall.controller..*.*(..))")
    public void wegLog(){

    }

    @Before("wegLog()")
    public void doBefore(JoinPoint joinPoint){
        //收到请求信息，
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        log.info("URL:"+ request.getRequestURL().toString());
        log.info("HTTP_METHOD:"+ request.getMethod());
        log.info("IP:"+ request.getRemoteAddr());
        log.info("CLASS_METHOD:"+ joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        log.info("ARGS:"+ Arrays.toString(joinPoint.getArgs()));
    }


    @AfterReturning(returning = "res", pointcut = "wegLog()")
    public void doAfter(Object res) throws JsonProcessingException {
        log.info("RESPONSE:"+ new ObjectMapper().writeValueAsString(res));
    }
}






















